package com.example.llm.learn.api.controller;

import com.example.llm.learn.api.dto.CommonResponse;
import com.example.llm.learn.api.dto.PageDTO;
import com.example.llm.learn.api.dto.SkuDTO;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin(origins = {"http://localhost:5173", "http://127.0.0.1:5500"})
@RestController
public class SkuController implements InitializingBean {
    private List<SkuDTO> list = new LinkedList<>();

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @PostMapping(value = "/sku/add")
    public CommonResponse<Boolean> add(@RequestBody SkuDTO skuDTO) {
        skuDTO.setId(System.currentTimeMillis());
        list.add(skuDTO);
        return CommonResponse.ok(Boolean.TRUE);
    }

    @GetMapping(value = "/sku/list")
    public CommonResponse<List<SkuDTO>> add(@RequestParam(value = "spuId") Long spuId) {
        return CommonResponse.ok(list.stream().filter(item -> spuId.equals(item.getSpuId())).collect(Collectors.toList()));
    }

    @GetMapping(value = "/sku/page")
    public CommonResponse<PageDTO<SkuDTO>> page(@RequestParam(required = false, defaultValue = "1") Integer pageNo,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        PageDTO<SkuDTO> page = new PageDTO<>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        List<SkuDTO> filterList = list.stream().filter(item -> true).toList();
        page.setTotal(filterList.size());
        int skip = Math.min(filterList.size(), (pageNo - 1) * pageSize);
        page.setList(filterList.stream().skip(skip).limit(pageSize).collect(Collectors.toList()));
        return CommonResponse.ok(page);
    }
}
